﻿using Furion.Schedule;
using Microsoft.Extensions.Logging;
using OAS.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OAS.Application
{
    public class AttendanceJob : IJob
    {
        private readonly ISqlSugarClient db;
        public AttendanceJob(ISqlSugarClient db)
        {
            this.db = db;
        }

        public Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
        {
            var list = db.Queryable<User>()
                 .LeftJoin(db.Queryable<Attendance>().Where(o=>o.RecordDate.Value.Date.Equals(DateTime.Now.Date)), (o, at) => o.UserName == at.UserName)
                 .LeftJoin<Role>((o, at, role) => o.Role_Id == role.Role_Id)
                 .Where((o, at, role) => role.RoleName != "总经理")
                 .Select((o, at, role) => new Attendance()
                 {
                     RecordID = at.RecordID,
                     UserName = at.UserName ?? o.UserName,
                     RecordDate = at.RecordDate ?? DateTime.Now,
                     ClockInTime = at.ClockInTime,
                     ClockOutTime = at.ClockOutTime,
                     Status = at.Status
                 }).ToList();
            foreach (var attendance in list)
            {
                if(attendance.ClockInTime is null || attendance.ClockOutTime is null)
                {
                    if(db.Queryable<Request>().Any(o => o.UserName == attendance.UserName && o.RequestType <= 1 && DateTime.Now.Date >= o.StartDate.Value.Date && DateTime.Now.Date <= o.EndDate.Value.Date)){
                        attendance.Status = 4;
                    }
                    else
                    {
                        attendance.Status = 0;
                    }
                }
                else if (attendance.ClockInTime.Value.Hour > 9)
                {
                    attendance.Status = 2;
                }
                else if (attendance.ClockInTime.Value.Hour < 6)
                {
                    attendance.Status = 3;
                }
                else
                {
                    attendance.Status = 1;
                }
            }
            db.Storageable(list).ExecuteCommand();
            return Task.CompletedTask;
        }
    }
}
